#include "stdafx.h"
#include "UserCertifier.h"

#include <atlconv.h>

#include "../../NSNetLibSrc/Framework/ServerFramework/ServerFramework_Database.h"
#include "../../NSNetLibSrc/Library/BSLib/Security/md5class.h"

DECLARE_SQL_QUERY_BEGIN(SQLCertifyUser, ProcedureQueryWithRecordset<sCertifyResult>)
	DECLARE_SQL_QUERY_PARAM_STRING(Id, 65)
	DECLARE_SQL_QUERY_PARAM_STRING(Password, 69)
DECLARE_SQL_QUERY_CONSTRUCT(SQLCertifyUser)
	DECLARE_SQL_QUERY_CONSTRUCT_INIT_PROC_WITH_RECORDSET(USP_VC_CERTIFY_USER)
	DECLARE_SQL_QUERY_CONSTRUCT_INIT_PARAM(Id, ADODB::ParameterInput, ADODB::DataVarWChar)
	DECLARE_SQL_QUERY_CONSTRUCT_INIT_PARAM(Password, ADODB::ParameterInput, ADODB::DataVarWChar)
DECLARE_SQL_QUERY_CONSTRUCT_INIT_END
	DECLARE_SQL_QUERY_CONSTRUCT_BIND_PARAM(Id)
	DECLARE_SQL_QUERY_CONSTRUCT_BIND_PARAM(Password)
DECLARE_SQL_QUERY_END

eCertificationResult UserCertifier_Default(sCertifyParam* pParam)
{
	size_t key_size = pParam->sessionKey.size();
	if (key_size < 4 || key_size > 256)
	{
		ReportLog(LOG_FATAL, L"invalid session key length[%d]", key_size );
		return eCR_Incorrect_SessionKey;
	}

	sQueryStatement statement;
	statement.m_pTrigger = nullptr;
	statement.m_RowSize = sizeof(sCertifyResult);
	statement.m_BufferSize = sizeof(sCertifyResult);

	size_t pos = pParam->sessionKey.find( '|' );
	if (pos == -1)
	{
		ReportLog( LOG_FATAL, L"invalid session key. no found section mark." );
		return eCR_Incorrect_SessionKey;
	}

	std::string id = pParam->sessionKey.substr(0, pos);
	std::string pw = pParam->sessionKey.substr(pos + 1);

	USES_CONVERSION;
	pParam->strUserID = A2W( id.c_str() );

	CMD5 md5;
	md5.setPlainText( pw.c_str() );

	std::string md5pwd;
	md5pwd = md5.getMD5Digest();

	std::wstring wmd5pwd = A2W( md5pwd.c_str() );

	SQLCertifyUser query;
	query.SetId( pParam->strUserID.c_str() );
	query.SetPassword( wmd5pwd.c_str() );
	statement.m_pQuery = &query;

	if( ExecQuery(g_database, statement) == false )
	{
		ReportLog( LOG_FATAL_FILE, L"query [%s] failed!", query.name() );
		return eCR_ServerInternalError;
	}

	const sCertifyResult& cert_result = query.recordsets().front();

	if (cert_result.user_id == 0)
		return eCR_Incorrect_ID_n_Password;

	pParam->dwJID = cert_result.user_id;
	pParam->user_security = cert_result.user_security;

	return eCR_Success;
}
